package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发布动态
    public String saveMovements(String textContent,
                                String location,
                                String longitude,
                                String latitude,
                                MultipartFile[] files) {
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        //图片上传
        ArrayList<String> imageUrls = new ArrayList<>();//保存图片上传之后的url
        for (MultipartFile file : files) {
            PicUploadResult uploadResult = picUploadService.upload(file);
            imageUrls.add(uploadResult.getName());//uploadResult的name属性设置为可直接下载该图片的网址
        }
        publish.setMedias(imageUrls);

        return quanZiApi.savePublish(publish);
    }

    private PageResult queryPublishList(User user, Integer page, Integer pageSize) {

        Long userId = null;
        PageInfo<Publish> pageInfo = null;

        if (null == user) {
            //查询推荐动态
            String key = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String value = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)) {
                //redis命中数据
                String[] pids = StringUtils.split(value, ",");
                int startIndex = (page - 1) * pageSize;
                if (startIndex < pids.length) {
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length) {
                        endIndex = pids.length - 1; //保证startIndex和endIndex都不要超出最大长度的范围
                    }

                    ArrayList<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }

                    List<Publish> publishList = quanZiApi.queryPublishByPids(pidList);
                    if (!CollectionUtils.isEmpty(publishList)) {
                        pageInfo = new PageInfo<>();
                        pageInfo.setRecords(publishList);
                    }
                }
            }
        }

        if (null == pageInfo) {
            //走默认查询逻辑,查询默认推荐列表
            if (null != user) {
                userId = user.getId();
            }
            pageInfo = quanZiApi.queryPublishList(userId, page, pageSize);//userId为null,则查询推荐动态,否则查询好友动态
        }

        user = UserThreadLocal.get();//在判断完是查询推荐动态还是好友动态之后,还是要将当前登录用户信息赋值给user,否则下面的点赞喜欢属性需要调用当前登录用户id作为redis中存储的key,会报空指针

        List<Publish> records = pageInfo.getRecords();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //未查询到动态数据
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }

        List<Movements> movementsList = fillMovementsValue(records);
        pageResult.setItems(movementsList);
        return pageResult;
    }

    private List<Movements> fillMovementsValue(List<Publish> records) {

        User user = UserThreadLocal.get();

        ArrayList<Movements> movementsList = new ArrayList<>();
        HashSet<Long> userIds = new HashSet<>(); //同一个用户可能会发布多条动态,我们只需要拿到一个userId即可

        for (Publish record : records) {

            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());

            //是否点赞:1点赞 0未点赞
            String likeCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
            //判断是否点赞,如果redis中存在likeCommentKey的key,则值一定为1,否则该key就不存在,直接被delete掉了,因此此处可以通过hasKey来做条件判断
            movements.setHasLiked(redisTemplate.hasKey(likeCommentKey) ? 1 : 0);

            //点赞数
            String likeCommentCountKey = "QUANZI_COMMENT_LIKE_" + movements.getId(); //publishId
            String likeCount = redisTemplate.opsForValue().get(likeCommentCountKey);
            //点赞总数,在redis中是通过自增自减进行操作的,即除非该key过期或第一次被访问,否则会一直存在
            if (StringUtils.isNotEmpty(likeCount)) { //当字符串为null或""时,返回false
                movements.setLikeCount(Integer.valueOf(likeCount));
            } else {
                movements.setLikeCount(0);
            }

            //是否喜欢:1点赞 0未点赞
            String loveCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
            movements.setHasLoved(redisTemplate.hasKey(loveCommentKey) ? 1 : 0);

            //喜欢数
            String loveCommentCountKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveCount = redisTemplate.opsForValue().get(loveCommentCountKey);
            if (StringUtils.isNotEmpty(loveCount)) { //当字符串为null或""时,返回false
                movements.setLoveCount(Integer.valueOf(loveCount));
            } else {
                movements.setLoveCount(0);
            }

            movements.setCommentCount(30); //TODO 评论数
            movements.setDistance("1.2公里"); //TODO 距离
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));//发布时间:算出跟当前时间的时间差
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movementsList.add(movements);

            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);

        for (Movements movements : movementsList) {

            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setTags(StringUtils.split(userInfo.getTags(), ","));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());
                    break;
                }
            }
        }
        return movementsList;
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {

        return this.queryPublishList(null, page, pageSize);
    }

    public PageResult queryFriendPublishList(Integer page, Integer pageSize) {

        return this.queryPublishList(UserThreadLocal.get(), page, pageSize);
    }

    public Long likeComment(String publishId) {

        User user = UserThreadLocal.get();

        boolean bool = quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!bool) {
            //保存点赞失败
            return null;
        }

        //因动态的点赞数使用量较大,因此要保存至redis中进行缓存
        Long likeCount = 0L;
        String likeCommentCountKey = "QUANZI_COMMENT_LIKE_" + publishId;
        if (!redisTemplate.hasKey(likeCommentCountKey)) {
            //redis缓存中没有,就去mongodb中拿并缓存至redis中
            Long count = quanZiApi.queryCommentCount(publishId, 1);
            likeCount = count;
            redisTemplate.opsForValue().set(likeCommentCountKey, String.valueOf(likeCount));
        } else {
            //redis缓存中有则拿出来做自增操作
            likeCount = redisTemplate.opsForValue().increment(likeCommentCountKey);
        }

        //记录当前登录用户对该动态进行点赞的标记到redis中
        String likeCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(likeCommentKey, "1");

        return likeCount;
    }

    public Long dislikeComment(String publishId) {

        User user = UserThreadLocal.get();

        boolean bool = quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!bool) {
            return null;
        }

        //取消点赞,则redis中的点赞数需减少1
        String likeCommentCountKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = redisTemplate.opsForValue().decrement(likeCommentCountKey);

        //删除redis中记录的当前登录用户对该动态进行点赞的标记
        String likeCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.delete(likeCommentKey);

        return count;
    }

    public Long loveComment(String publishId) {

        User user = UserThreadLocal.get();

        boolean bool = quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            //保存喜欢失败
            return null;
        }

        //因动态的喜欢数使用量较大,因此要保存至redis中进行缓存
        Long loveCount = 0L;
        String loveCommentCountKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!redisTemplate.hasKey(loveCommentCountKey)) {
            //redis缓存中没有,就去mongodb中拿并缓存至redis中
            Long count = quanZiApi.queryCommentCount(publishId, 1);
            loveCount = count;
            redisTemplate.opsForValue().set(loveCommentCountKey, String.valueOf(loveCount));
        } else {
            //redis缓存中有则拿出来做自增操作
            loveCount = redisTemplate.opsForValue().increment(loveCommentCountKey);
        }

        //记录当前登录用户对该动态进行喜欢的标记到redis中
        String loveCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(loveCommentKey, "1");

        return loveCount;
    }

    public Long unloveComment(String publishId) {

        User user = UserThreadLocal.get();

        boolean bool = quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!bool) {
            return null;
        }

        //取消喜欢,则redis中的点赞数需减少1
        String loveCommentCountKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = redisTemplate.opsForValue().decrement(loveCommentCountKey);

        //删除redis中记录的当前登录用户对该动态进行喜欢的标记
        String loveCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.delete(loveCommentKey);

        return count;
    }

    public Movements queryMovementsById(String publishId) {

        Publish publish = quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }
        //在发布表中查询到该publishId对应的动态信息,后将相关数据填充到Movements对象中
        List<Movements> movementsList = this.fillMovementsValue(Arrays.asList(publish));

        return movementsList.get(0);//该集合中只有一个元素
    }

    public List<VisitorsVo> queryVisitorsList() {

        User user = UserThreadLocal.get();

        //如果redis中存在上一次查询的时间点,则按照时间查询,否则按照数量查询
        String key = "visitors_" + user.getId();
        String data = redisTemplate.opsForValue().get(key);

        List<Visitors> visitorsList = null;
        if (StringUtils.isEmpty(data)) {
            //按照数量查询
            visitorsList = visitorsApi.topVisitor(user.getId(), 6);//商量后给默认值
        } else {
            //按照时间查询
            visitorsList = visitorsApi.topVisitor(user.getId(), Long.valueOf(data));
        }

        if (CollectionUtils.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        HashSet<Long> visitorUserIds = new HashSet<>();
        for (Visitors visitors : visitorsList) {
            visitorUserIds.add(visitors.getVisitorUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", visitorUserIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        ArrayList<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            for (UserInfo userInfo : userInfoList) {

                if (visitors.getVisitorUserId().longValue() == userInfo.getUserId().longValue()) {

                    VisitorsVo visitorsVo = new VisitorsVo();

                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitors.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        redisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis()), 24L, TimeUnit.HOURS);

        return visitorsVoList;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }
        List<Movements> movementsList = this.fillMovementsValue(records);
        pageResult.setItems(movementsList);
        return pageResult;
    }
}
